package com.tc.nio.c5;

import com.tc.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;

/**
 * @Auther: tianchao
 * @Date: 2022/2/10 10:21
 * @Description:
 */
@Slf4j
public class AioFileChannel {


    public static void main(String[] args) throws IOException, InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try(
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)
        ) {
            //接收的结果
            ByteBuffer dst = ByteBuffer.allocate(16);
            //读取的起始位置
            long position = 0;
            //附件 一个bytebuffer不够用 通过附件接着读
            //包含了两个回调方法的回调对象
            channel.read(dst, position, dst, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("CompletionHandler.complated....参数1:{},参数2: {}",result,attachment);
                    attachment.flip();
                    ByteBufferUtil.debugAll(attachment);
                    countDownLatch.countDown();
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    log.debug("CompletionHandler.failed....参数1:{},参数2: {}",exc,attachment);
                }
            });
            log.debug("read end...");
        } catch (IOException e) {
            e.printStackTrace();
        }
        countDownLatch.await();
        log.debug("读线程执行完成");
    }
}
